import {fabric} from 'fabric';
import gsApi from '@/api/gsApi'
export default class ShowPosition{
  img = ''
  canvas = null
  position = null
  intervalFlag = null
  locatTri = null
  constructor(img,canvas){  
    this.img = img;
    this.canvas = canvas;
  }

  //先用下面的show显示位置，再用这个函数更新位置
  moveCurrentPosition(point){
    let imgHeight = this.img.height;
    let left = point.gridPosition.x;
    let top = imgHeight-point.gridPosition.y;
    let angle = -point.angle+90;
    // console.log(left + ' ' + top + ' ' + angle)
    //1.用重新打点的方式显示实时位置
    // this.locatTri.set("left",left);
    // this.locatTri.set("top",top)
    // this.locatTri.set("angle",angle)
    // this.canvas.renderAll()
    //2.用动画的效果处理
    this.locatTri.animate('left',left,{
      onChange: this.canvas.renderAll.bind(this.canvas)
    })
    this.locatTri.animate('top',top,{
      onChange: this.canvas.renderAll.bind(this.canvas)
    })
    this.locatTri.animate('angle',angle,{
      onChange: this.canvas.renderAll.bind(this.canvas)
    })
  }

  //小车移动时实时显示当前位置点
  showCurrentPosition(point){
    console.log('--------------------')
    console.log(this.img)
    console.log(this.canvas)
    // this.canvas.remove(this.locatTri)
    let imgHeight = this.img.height;
    this.locatTri=new fabric.Triangle({
      height:10,
      width:6,
      // radius: 4,
      fill: '#FFD700',
      stroke: 'red',
      strokeWidth: 0.5,
      angle:-point.angle+90,    //角度要注意转换！
      left: point.gridPosition.x,
      //  记得需要转换坐标系的，canvas 上显示坐标系 和 机器人导航的坐标系
      top: imgHeight-point.gridPosition.y,
      selectable: false,
      hasBorders: false,
      hasControls: false,
      originX: 'center',
      originY: 'center',
    })
    // console.log(this.canvas.getObjects())
    this.canvas.add(this.locatTri);
  }
  async location(){
    const res=await gsApi.getLocation()
    this.position=res.data;
    // console.log(this.currentPosition);
  }
  async showPosition(){
    await this.location()
    console.log(this.position)
    this.showCurrentPosition(this.position);
    clearInterval(this.intervalFlag)
    this.intervalFlag = setInterval(async () => {
        //const res = await gsApi.getLocation()
        //不能直接这样写，会报错
        await this.location();
        this.moveCurrentPosition(this.position);
      }, 500);
  }
}